//
//  main.c
//  C_11网络与套接字
//
//  Created by Robin on 16/3/21.
//  Copyright © 2016年 cnbm. All rights reserved.
//

#include <stdio.h>
#include <stdlib.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <signal.h>

/**
 BLAB (绑定,监听,接受,开始通信)
 */

void error (char *msg){
    printf("%s : %s\n",msg,strerror(errno));
    exit(1);
}

int main(int argc, const char * argv[]) {

//    // 创建一个互联网30000 的套接字名
//    struct sockaddr_in name;
//    name.sin_family = PF_INET;
//    name.sin_port = (in_port_t)htons(30000);
//    name.sin_addr.s_addr = htonl(INADDR_ANY);
    
    char *advices[] = {"Take smaller bites\r\n",
                     "Go for tight jeanz\r\n",
                     "One word : inappropriate\r\n",
                     "Just today,Love me\r\n"
                     };
    
    // 创建套接字
    int listener_d = socket(PF_INET, SOCK_STREAM, 0);
    
    // 创建一个互联网30000的套接字端口
    struct sockaddr_in name;
    name.sin_family = PF_INET;
    name.sin_port = (in_port_t)htons(30000);
    name.sin_addr.s_addr = htonl(INADDR_ANY);
    
    // 服务器绑定端口有延迟
    int reuse = 1;
    if (setsockopt(listener_d, SOL_SOCKET, SO_REUSEADDR, (char *)&reuse, sizeof(int))) {
        error("无法设置套接字的 '重新使用端口选项' ");
    }
    
    // 把套接字绑定到 30000 端口
    if (bind(listener_d, (struct sockaddr *) &name, sizeof(name)) == -1) {
        error("Cannot bind the port");
    }
    
    listen(listener_d, 10); // 监听端口,并把队列长度设为10;
    
    puts("Wating for connection....");
    while (1) { // 需要循环接受,然后开始对话
        struct sockaddr_storage client_addr;
        unsigned int addr_size = sizeof(client_addr);
        
        int connect_d = accept(listener_d, (struct sockaddr *)&client_addr, &addr_size);
     
        char *msg = advices[rand()%5];
        
        send(connect_d, msg, strlen(msg), 0);
        close(connect_d);
    }
    return 0;
}
